package com.showcai.utils;

import com.showcai.module.wechat.WXJSConfig;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class WeiXinUtils {
    private static final String str = null;
    private static Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);
    /**
     * 应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），snsapi_userinfo
     * （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，即使在未关注的情况下，只要用户授权，也能获取其信息）
     */
    public static final String SNSAPI_BASE = "snsapi_base";
    public static final String SNSAPI_USERINFO = "snsapi_userinfo";
    public static final Long EXPIREIN = 7000*1000l;

    public static   Map<String,String> jsTicket =new HashMap<>();


    /**
     * 微信鉴权URL
     *
     * @param url   鉴权URL后返回的URL
     * @param scope 鉴权方式
     * @return
     */
    public static String oauth2(String url, String scope) {
        String urlE = url;
        try {
            urlE = URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String s = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + FixedData.ENTERPRISE_APP_ID + "&redirect_uri=" + urlE
                + "&response_type=code&scope=" + scope + "&state=STATE#wechat_redirect";
        return s;
    }

    /**
     * @return 签名, sign字段不参加签名
     * @生成签名，详见签名生成算法
     */
    public static String MakeSign(String... arry) {

        Arrays.sort(arry);
        StringBuilder sb = new StringBuilder();
        for (String a : arry) {

            if (StringUtils.isNotBlank(a)) {
                sb.append(a);
            }

        }
        // return genStr(sb.toString());

        System.out.println(sb.toString());
        return sb.toString();
    }

    public static String getSort(Map<String, String> map) {

        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        StringBuilder stringA = new StringBuilder();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            if (StringUtils.isNotBlank(entry.getValue())) {
                stringA.append(entry.getKey() + "=" + entry.getValue());

                if (it.hasNext()) {
                    stringA.append("&");
                }
            }
        }
        return stringA.toString();
    }

    public static String MakeSign(Map<String, String> map, String key) {
        String stringSignTemp = getSort(map);
        logger.info("stringSignTemp+=========" + stringSignTemp);
        if (StringUtils.isNotBlank(key)) {
            stringSignTemp += "&key=" + key;
        }
        logger.info("stringSignTemp+=========" + stringSignTemp);
        String sign = MD5Tools.MD5(stringSignTemp).trim().toUpperCase();
        logger.info("sign===========>" + sign);
        return sign;
    }
    //String ticket = weChatService.getTicket(appID, JsapiTicket.TYPE_TICKET);
    public static WXJSConfig getWXConfig(String appID, String url, String ticket) throws MyRunTimeExcption {

        if (org.apache.commons.lang.StringUtils.isBlank(appID)) {
            throw new MyRunTimeExcption("appID is null");
        }
        Map<String, String> map = new TreeMap<String, String>();
        String timeStamp = DateUtil.DateToTimestamp(new Date()).toString();
        map.put("timestamp", timeStamp);
        WXJSConfig wxJSConfig = new WXJSConfig();
        wxJSConfig.setAppId(appID);
        wxJSConfig.setTimestamp(timeStamp);
        wxJSConfig.setDebug(true);
        String nonceStr = GenerateID.getUUID().toUpperCase();
        map.put("noncestr", nonceStr);
        wxJSConfig.setNonceStr(nonceStr);

        map.put("url", url);
        map.put("jsapi_ticket", ticket);
        String Str1 = WeiXinUtils.getSort(map);
        logger.info("getWXConfigStr1   ====================" + Str1);
        String signature = null;
        try {
            signature = SHA1.genStr(Str1);
        } catch (NoSuchAlgorithmException e) {
            logger.info("NoSuchAlgorithmException====================>>>>>>>>>>>>>>>>>>>"+e.getMessage());
            e.printStackTrace();
            throw new MyRunTimeExcption(e.getMessage());
        }
        logger.info("getWXConfig signature====================" + signature);
        wxJSConfig.setSignature(signature);
        wxJSConfig.setJsApiList(Str1 + "<p>" + signature);
        return wxJSConfig;
    }


}
